﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using ZoLone.Custom;
using ZoLone.Models;
using ZoLone.Models.Sys;
using ZoLone.Zo.Extensions;

namespace ZoLone.Areas.Admin.Controllers
{

    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    [AdminActionFilter]
    public class BaseController : Controller
    {
        /// <summary>
        /// 当前用户信息
        /// </summary>
        public Account _Account { get; set; } = new Account();

        /// <summary>
        /// 菜单组
        /// </summary>
        public List<Sys_Operation> _Menus { get; set; }


        [NonAction]
        public IActionResult Success()
        {
            return new JsonResult(new { status = 1 } );
        }
        [NonAction]
        public IActionResult Success(object data, string msg)
        {
            return new JsonResult(new { status = 1, data, msg });
        }

        [NonAction]
        public IActionResult Success(object data)
        {
            return new JsonResult(new { status = 1, data });
        }

        [NonAction]
        public IActionResult Error()
        {
            return new JsonResult(new { status = 0 } );
        }

        [NonAction]
        public IActionResult Error(object data, string msg)
        {
            return new JsonResult(new { status = 0, msg, data });
        }
        [NonAction]
        public IActionResult Error(string msg)
        {
            return new JsonResult(new { status = 0, msg } );
        } 
        
        public bool IsAjax()
        {
            return Request.IsAjax();
        }
    }
    //jq datatable插件用的实体model
    public class TableBsEntity<T>
    {
        /// <summary>
        /// 请求次数（前端==》后端）
        /// </summary>
        public int draw { get; set; }

        /// <summary>
        /// 总记录数（前端《==后端）
        /// </summary>
        public int recordsTotal { get; set; }

        /// <summary>
        /// 过滤后的总记录数（前端《==后端）
        /// </summary>
        public int recordsFiltered { get; set; }

        /// <summary>
        /// 记录开始索引（前端==》后端）
        /// </summary>
        public int start { get; set; }

        /// <summary>
        /// PageSize（前端==》后端）
        /// </summary>
        public int length { get; set; }

        /// <summary>
        /// 集合分页数据（前端《==后端）
        /// </summary>
        public List<T> data { get; set; }
    }
    //返回分部视图Html
    public static class MvcRender
    {
        /// <summary>
        /// 返回分部视图Html
        /// </summary>
        /// <param name="viewName">视图路径</param>
        /// <param name="partial">是否分部页</param>
        /// <returns></returns>
        public static async Task<string> RenderViewAsync(this Controller controller, string viewName, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }

            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    throw new Exception($"A view with the name {viewName} could not be found");
                }
                ViewContext viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    writer,
                    new HtmlHelperOptions()
                );
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
        /// <summary>
        /// 返回分部视图Html
        /// </summary>
        /// <typeparam name="TModel">数据模型</typeparam>
        /// <param name="viewName">视图名称</param>
        /// <param name="model">数据实例</param>
        /// <param name="partial">是否分部页</param>
        /// <returns></returns>
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }
            if (model != null)
            {
                controller.ViewData.Model = model;
            }

            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    throw new Exception($"A view with the name {viewName} could not be found");
                }
                ViewContext viewContext = new ViewContext(
                    controller.ControllerContext,
                    viewResult.View,
                    controller.ViewData,
                    controller.TempData,
                    writer,
                    new HtmlHelperOptions()
                );
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
    }
   

}
